using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace XLFrame
{
    /// <summary>
    /// 使Json.Net可以正确序列化或反序列化Unity中的Vector数据
    /// 不支持TypeNameHandling.All和Auto 如果要用object存储 建议配合JsonObject
    /// </summary>
    public class UnityJsonConverter : JsonConverter
    {
        public override bool CanRead => true;
        public override bool CanWrite => true;

        private static readonly HashSet<Type> UnityValueTypes = new HashSet<Type>
        {
            typeof(Vector2),
            typeof(Vector2Int),
            typeof(Vector3),
            typeof(Vector3Int),
            typeof(Vector4),
            typeof(Color),
            typeof(Quaternion),
            typeof(Rect),
            typeof(Bounds),
            typeof(Matrix4x4)
        };

        public override bool CanConvert(Type objectType)
        {
            return UnityValueTypes.Contains(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
           return JsonUtility.FromJson(JObject.Load(reader).ToString(), objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JObject keyValuePairs = JObject.Parse(JsonUtility.ToJson(value));
            keyValuePairs.WriteTo(writer);
        }
    }
}
